package quick.communication;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;


public class HttpClient {

    private static final OkHttpClient mOkHttpClient = new OkHttpClient();


    static 
    {
        mOkHttpClient.setConnectTimeout(300, TimeUnit.SECONDS);
    }

    /**
     * 同步执行一个请求，返回请求结果。
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static Response execute(Request request) throws IOException {
        return mOkHttpClient.newCall(request).execute();
    }
    
    /**
     * 同步执行一个请求，返回请求结果。
     * @param url
     * @return
     * @throws IOException
     */
    public static String execute(String url) throws IOException {
        Request request = new Request.Builder().url(url).build();
        Response response = execute(request);
        if (response.isSuccessful()) {
            String responseUrl = response.body().string();
            return responseUrl;
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * 异步执行一个请求，请求结果。
     *
     * @param request
     * @param httpResponseHandler
     */
    public static void enqueue(Request request, final AsyncHttpResponseHandler httpResponseHandler) {
    	
        mOkHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onResponse(Response response) throws IOException {
                httpResponseHandler.sendSuccessMessage(response);
            }

            @Override
            public void onFailure(Request request, IOException e) {
                httpResponseHandler.sendFailureMessage(request, e);
            }
        });
    }

    /**
     * 异步执行一个请求，忽略请求结果。
     *
     * @param request
     */
    public static void enqueue(Request request) {
        mOkHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onResponse(Response arg0) throws IOException {

            }

            @Override
            public void onFailure(Request arg0, IOException arg1) {

            }
        });
    }

    

    /**
     * 格式化参数。
     *
     * @param params
     * @return
     */
    public static String formatParams(List<BasicNameValuePair> params) {
        return URLEncodedUtils.format(params, "UTF-8");
    }

    /**
     * 为HttpGet 的 url 方便的添加多个name value 参数。
     *
     * @param url
     * @param params
     * @return
     */
    public static String attachHttpGetParams(String url, List<BasicNameValuePair> params) {
        url = url + "?" + formatParams(params);
        return url;
    }

    /**
     * 为HttpGet 的 url 方便的添加1个name value 参数。
     *
     * @param url
     * @param name
     * @param value
     * @return
     */
    public static String attachHttpGetParam(String url, String name, String value) {
        return url + "?" + name + "=" + value;
    }

    /**
     * 网络是否连接
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        try {
            ConnectivityManager connectivityManager =  (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return false;
    }


    public static void get(String url, List<BasicNameValuePair> params, AsyncHttpResponseHandler httpResponseHandler) {
    	
        Request request = new Request.Builder().url(attachHttpGetParams(url, params)).build();
        enqueue(request, httpResponseHandler);
    }
    
    /**
     * Post提交，并返回结果
     * @param url
     * @param params
     * @param httpResponseHandler
     */
    public static void post(String url, List<BasicNameValuePair> params, AsyncHttpResponseHandler httpResponseHandler) {
    	
    	FormEncodingBuilder formBulder = new FormEncodingBuilder();
    	for(BasicNameValuePair value:params)
    	{
    		formBulder.add(value.getName(), value.getValue());
    	}
    	
    	RequestBody body = formBulder.build();
    	
        Request request = new Request.Builder().url(url).post(body).build();
        enqueue(request, httpResponseHandler);
    }
}
